//
//  AppDelegate.m
//  VehicleNetStore
//
//  Created by xxcao on 2017/6/20.
//  Copyright © 2017年 MobileArtisan. All rights reserved.
//
#import "AppDelegate.h"
#import "VNSMainViewController.h"
#import "NotificationManager.h"
#import "ZJLeadingPageController.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "AESCrypt.h"
#import "Common.h"

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
//微信SDK头文件
#import "WXApi.h"
//新浪微博SDK头文件
#import "WeiboSDK.h"
//新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加”-ObjC”


@interface AppDelegate ()
@end


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if (!self.window) {
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *aesValue = [userDefaults objectForKey:@"firstLaunch"];
    if ([Common isEmptyString:aesValue]) {
        [userDefaults setObject:@"1" forKey:@"firstLaunch"];
        [userDefaults synchronize];
        ZJLeadingPageController *leadController = [[ZJLeadingPageController alloc] initWithPagesCount:3 setupCellHandler:^(ZJLeadingPageCell *cell, NSIndexPath *indexPath) {
            // 设置图片
            NSString *imageName = [NSString stringWithFormat:@"%ld.jpeg",(long)indexPath.row];
            cell.imageView.image = [UIImage imageNamed:imageName];
            
            // 设置按钮属性
            [cell.finishBtn setTitle:@"立即体验" forState:UIControlStateNormal];
            [cell.finishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [cell.finishBtn setBackgroundColor:[UIColor orangeColor]];
            
        } finishHandler:^(UIButton *finishBtn) {
            VNSMainViewController *mainViewController = [[VNSMainViewController alloc] init];
            mainViewController.first = YES;
            self.window.rootViewController = mainViewController;
        }];
        leadController.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        leadController.pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
        
        self.window.rootViewController = leadController;
    } else {
        VNSMainViewController *mainViewController = [[VNSMainViewController alloc] init];
        self.window.rootViewController = mainViewController;
    }
    [self initGlobalSetting];
    [self registeShareSDK];
    [self.window makeKeyAndVisible];
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
}

//MARK: - Notification
/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[
                                                                                  NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    // 向个推服务 注册deviceToken
    [[NotificationManager sharedInstance] registerDeviceToken:token];
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}

#pragma mark - APP运行中接收到通知(推送)处理 - iOS 10以下版本收到推送

/** APP已经接收到“远程”通知(推送) - 透传推送消息  */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    
#warning 点击通知消息进去app iOS10以下
    // 控制台打印接收APNs信息
    NSLog(@"\n>>>[Receive RemoteNotification]:%@\n\n", userInfo);
    //to do 解析消息进入app iOS10以下
    if (!iOS10) {
        [[NotificationManager sharedInstance] handleAMessage:userInfo Type:EPushResponseIOS10Below];
        
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)initGlobalSetting {
    NotificationManager *notificationManager = [NotificationManager sharedInstance];
    [notificationManager startPush];
    [self reachability];
    
}

- (void)reachability {
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                break;
        }
        
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
            NSLog(@"有网");
        } else {
            [SVProgressHUD showErrorWithStatus:@"您的网络好像有问题~"];
            [SVProgressHUD dismissWithDelay:2.0];
        }
    }];
    // 3.开始监控
    [mgr startMonitoring];
}


- (AFSecurityPolicy*)customSecurityPolicy {
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"https" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    NSLog(@"certData:%@", certData);
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    [securityPolicy setAllowInvalidCertificates:NO];
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    [securityPolicy setValidatesDomainName:YES];
    [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]];
    return securityPolicy;
}


- (void)uploadClient_Id {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //https ssl 验证。
    //    [manager setSecurityPolicy:[self customSecurityPolicy]];
    [manager POST:kProUploadUrl parameters:@{@"clientId":self.clientId,
                                             @"customerId":self.userId} progress:^(NSProgress * _Nonnull uploadProgress) {
                                                 
                                             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                 NSLog(@"%@", responseObject);
                                                 NSLog(@"dic:%@", [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]);
                                             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                 NSLog(@"%@", error);
                                             }];
}

- (void)registeShareSDK {
    /*
     //＝＝＝＝＝＝＝＝＝＝ShareSDK头文件＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
     #import <ShareSDK/ShareSDK.h>
     #import <ShareSDKConnector/ShareSDKConnector.h>
     //以下是ShareSDK必须添加的依赖库：
     //1、libicucore.dylib
     //2、libz.dylib
     //3、libstdc++.dylib
     //4、JavaScriptCore.framework
     
     //＝＝＝＝＝＝＝＝＝＝以下是各个平台SDK的头文件，根据需要继承的平台添加＝＝＝
     //腾讯开放平台（对应QQ和QQ空间）SDK头文件
     #import <TencentOpenAPI/TencentOAuth.h>
     #import <TencentOpenAPI/QQApiInterface.h>
     //以下是腾讯SDK的依赖库：
     //libsqlite3.dylib
     
     //微信SDK头文件
     #import "WXApi.h"
     //以下是微信SDK的依赖库：
     //libsqlite3.dylib
     
     //新浪微博SDK头文件
     #import "WeiboSDK.h"
     //新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"
     //以下是新浪微博SDK的依赖库：
     //ImageIO.framework
     //libsqlite3.dylib
     //AdSupport.framework
     
     
     */
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http:mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。我们Demo提供的appKey为内部测试使用，可能会修改配置信息，请不要使用。
     *  方法中的第二个参数用于指定要使用哪些社交平台，以数组形式传入。第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeSinaWeibo),
                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformTypeQQ)
                                        ]
                             onImport:^(SSDKPlatformType platformType) {
                                 
                                 switch (platformType)
                                 {
                                     case SSDKPlatformTypeWechat:
                                         //                             [ShareSDKConnector connectWeChat:[WXApi class]];
                                         [ShareSDKConnector connectWeChat:[WXApi class] delegate:self];
                                         break;
                                     case SSDKPlatformTypeQQ:
                                         [ShareSDKConnector connectQQ:[QQApiInterface class]
                                                    tencentOAuthClass:[TencentOAuth class]];
                                         break;
                                     case SSDKPlatformTypeSinaWeibo:
                                         [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                                         break;
                                     default:
                                         break;
                                 }
                             }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
                          
                          switch (platformType)
                          {
                              case SSDKPlatformTypeSinaWeibo:
                                  //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                                  [appInfo SSDKSetupSinaWeiboByAppKey:@"483721469"
                                                            appSecret:@"42287175cee81febb98e952e481fe858"
                                                          redirectUri:@"http://www.sharesdk.cn"
                                                             authType:SSDKAuthTypeBoth];
                                  break;
                              case SSDKPlatformTypeWechat:
                                  [appInfo SSDKSetupWeChatByAppId:@"wxcc09d1769bc3e841"
                                                        appSecret:@"b57d92b949efc13e60599245d8745ac3"];
                                  break;
                              case SSDKPlatformTypeQQ:
                                  [appInfo SSDKSetupQQByAppId:@"1106365830"
                                                       appKey:@"2Lb1oPQokMXyzIn9"
                                                     authType:SSDKAuthTypeBoth];
                                  break;
                              default:
                                  break;
                          }
                      }];
}

@end
